package com.rank.ccms.service.impl;

import com.rank.ccms.domain.dao.UserDao;
import com.rank.ccms.domain.exception.DaoException;
import com.rank.ccms.domain.model.UserEntity;
import com.rank.ccms.service.UserService;
import com.rank.ccms.util.exception.ServiceException;
import com.rank.ccms.service.model.User;
import com.rank.ccms.util.security.PermissionType;
import com.rank.ccms.util.security.SecurityConstraint;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.security.auth.login.CredentialNotFoundException;
import javax.security.auth.login.LoginException;
import java.util.List;

/**
 * User: iru
 * Date: Feb 10, 2010
 * Time: 5:38:26 PM
 */
@Service("userService")
public class UserServiceImpl extends GenericServiceSupport<UserEntity, Long> implements UserService {

    @Resource(name = "userDao")
    private UserDao dao;

    public User login(String userName, String password) throws ServiceException, LoginException {
        UserEntity userEntity = dao.findByUserName(userName);
        if (userEntity == null) {
            throw new CredentialNotFoundException("The user with name '"+userName+"' not found.");
        } else if (!userEntity.getPassword().equals(password)) {
            throw new CredentialNotFoundException("The provided password is incorrect.");
        } else {
            userEntity.setOnline(true);
            try {
                dao.update(userEntity);
            } catch (DaoException e) {
                log.error(e.getMessage(), e);
                throw new ServiceException(e);
            }
            return new User(userEntity);
        }
    }

    public void logout(User user) throws ServiceException {
        try {
            UserEntity userEntity = dao.findById(user.getId());
            userEntity.setOnline(false);
            dao.update(userEntity);
        } catch (DaoException e) {
            throw new ServiceException(e);
        }
    }

    public UserDao getDao() {
        return dao;
    }

    public void setDao(UserDao dao) {
        this.dao = dao;
    }
}
